package eip.chapter5.sequence;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

public abstract class AbstractCheckoutBillService implements CheckoutBillService { 

	private static final Logger logger = Logger.getLogger(AbstractCheckoutBillService.class);
	protected Map<String, ArrayList<BillIdentifierWrapper>> billMap = 
		new TreeMap<String, ArrayList<BillIdentifierWrapper>>();
	
	public void processBill(BillIdentifierWrapper billWrapper) {
		addBillToMap(billWrapper);
		Boolean isLastBill = billWrapper.getBill().getLastBill();
		String guestName = billWrapper.getBill().getGuestName();
		try {
			if(isLastBill != null && isLastBill.booleanValue()) {
				sendCheckoutBill(guestName);
				billMap.remove(guestName);;
			}
		} catch(Exception e) {
			logger.error("error while sending checkoutbill to guest " + guestName, e);
		}
	}
	
	protected abstract void sendCheckoutBill(String guestName) throws Exception;
	
	protected void addBillToMap(BillIdentifierWrapper billWrapper) {
		if(billMap.containsKey(billWrapper.getBill().getGuestName())) {
			ArrayList<BillIdentifierWrapper> billList = billMap.get(billWrapper.getBill().getGuestName());
			billList.add(billWrapper);
		} else {
			ArrayList<BillIdentifierWrapper> billList = new ArrayList<BillIdentifierWrapper>();
			billList.add(billWrapper);
			billMap.put(billWrapper.getBill().getGuestName(), billList);
		}
	}
	
	protected abstract Object getCorrelationID(ArrayList<BillIdentifierWrapper> billList);
	
}
